package com.onenine.app.fragment;

import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.onenine.app.R;
import com.onenine.app.activity.InviteReplyCreateActivity;
import com.onenine.app.activity.UserDetailActivity;
import com.onenine.app.adapter.PostCommentAdapter;
import com.onenine.app.event.CommentScrollEvent;
import com.onenine.app.event.RefreshEvent;
import com.onenine.app.model.CommentParent;
import com.onenine.app.model.SpcCount;
import com.onenine.app.request.GetCommentRequest;
import com.onenine.app.response.DynamicDetailResponse;
import com.onenine.app.response.GetCommentResponse;
import com.onenine.app.response.PostDetailResponse;
import com.onenine.app.utils.CHelper;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.GlideUtils;
import com.onenine.app.utils.RoleResLoader;
import com.onenine.app.utils.UrlConfig;
import com.onenine.app.view.SpcCountBar;
import com.onenine.base.model.PageInfo;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.base.utils.AppConfig;
import com.onenine.base.view.NiceImageView;
import com.onenine.base.view.PullLoadMoreView;
import com.onenine.chat.rongcloud.RcUser;
import com.onenine.common.util.ApUtils;
import com.onenine.common.util.FragmentUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * 帖子详情内容
 */
public class PostDetailFragment extends Fragment implements BaseQuickAdapter.RequestLoadMoreListener {

    private SpcCountBar mSpcCountBar;
    private NiceImageView mAvatarView;
    private RecyclerView mRvDetail;
    private PostCommentAdapter mAdapter;
    private View mHeadView, mContentView, mInviteReplyView;
    private TextView mTvName, mTvDate, mTvCommentTitle;
    private String mPostId;
    private boolean isComment;
    private int mPostType;
    private int mPageNum = 1;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    /**
     * 设置帖子类型
     *
     * @param postId
     * @param postType
     * @return
     */
    public PostDetailFragment bindPostIdType(String postId, int postType) {
        this.mPostId = postId;
        this.mPostType = postType;
        return this;
    }

    /**
     * 设置详情内容
     *
     * @param spanType
     * @param detailResponse
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public PostDetailFragment bindPostDetail(int spanType, boolean isComment, PostDetailResponse detailResponse) {
        if (detailResponse == null) {
            return this;
        }
        this.isComment = isComment;
        showTopicContentFragment(detailResponse.getUserType(), spanType, detailResponse.getPvType()
                , detailResponse.getSex(), detailResponse.getPostDesc(), detailResponse.getPostPvUrl());
        bindUserInfoView(detailResponse.getUserId(), detailResponse.getNickName()
                , detailResponse.getSex(), detailResponse.getPhoto(), detailResponse.getDate());
        showSpcCount(mPostType, spanType, detailResponse);
        if (mPostType == DataType.POST_ASK) {
            showInviteReply(detailResponse.getAnswersNum(), detailResponse.getPostDesc());
        }
        return this;
    }

    /**
     * 设置详情内容
     *
     * @param spanType
     * @param detailResponse
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public PostDetailFragment bindDynamicDetail(int spanType
            , boolean isComment, DynamicDetailResponse detailResponse) {
        if (detailResponse == null) {
            return this;
        }
        this.isComment = isComment;
        showSpcCount(mPostId, mPostType, spanType, detailResponse);
        showTopicContentFragment(DataType.POST_USER, spanType, detailResponse.getPvType()
                , detailResponse.getSex(), detailResponse.getDynamicDesc(), detailResponse.getPvUrl());
        bindUserInfoView(detailResponse.getUserId(), detailResponse.getNickName()
                , detailResponse.getSex(), detailResponse.getPhoto(), detailResponse.getDate());
        return this;
    }

    /**
     * 显示帖子点选评论内容
     */
    private void showSpcCount(int postType, int spanType, PostDetailResponse detailResponse) {
        SpcCount vpcCount = new SpcCount();
        vpcCount.setLikeNum(detailResponse.getLikeNum());
        vpcCount.setForwardNum(detailResponse.getForwardNum());
        vpcCount.setCommentNum(detailResponse.getCommentNum());
        vpcCount.setLikeBln(detailResponse.isLikeBln());
        mSpcCountBar.setVisibility(View.VISIBLE);
        String[] imgUrls = detailResponse.getPostPvUrl().split(",");
        if (imgUrls.length > 1 || !TextUtils.isEmpty(imgUrls[0])) {
            mSpcCountBar.setData(vpcCount, detailResponse.getPostPkId()
                    , postType, spanType, detailResponse.getPostDesc(), imgUrls[0]);
        } else {
            mSpcCountBar.setData(vpcCount, detailResponse.getPostPkId()
                    , postType, spanType, detailResponse.getPostDesc(), null);
        }
    }

    /**
     * 显示邀请问答
     */
    private void showInviteReply(int askCount, String postDesc) {
        mInviteReplyView.setVisibility(View.VISIBLE);
        TextView tvAskCount = mInviteReplyView.findViewById(R.id.tv_ask_count);
        tvAskCount.setText(askCount + "个回答");
        View btnInvite = mInviteReplyView.findViewById(R.id.btn_invite_reply);
        btnInvite.setBackgroundResource(RoleResLoader
                .getRoleDrawableResourceId(RoleResLoader.DynamicResName.THEME_GRADIENT_CORNER_BG));
        btnInvite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InviteReplyCreateActivity.launchActivity(getActivity(), mPostId, postDesc);
            }
        });
    }

    /**
     * 显示动态点选评论内容
     */
    private void showSpcCount(String dynamicId, int postType, int spanType, DynamicDetailResponse detailResponse) {
        SpcCount vpcCount = new SpcCount();
        vpcCount.setLikeNum(detailResponse.getLikeNum());
        vpcCount.setForwardNum(detailResponse.getForwardNum());
        vpcCount.setCommentNum(detailResponse.getCommentNum());
        vpcCount.setLikeBln(detailResponse.isLikeBln());
        mSpcCountBar.setVisibility(View.VISIBLE);
        String[] imgUrls = detailResponse.getPvUrl().split(",");
        if (imgUrls.length > 1 || !TextUtils.isEmpty(imgUrls[0])) {
            mSpcCountBar.setData(vpcCount, dynamicId, postType, spanType
                    , detailResponse.getDynamicDesc(), imgUrls[0]);
        } else {
            mSpcCountBar.setData(vpcCount, dynamicId, postType, spanType
                    , detailResponse.getDynamicDesc(), null);
        }
    }

    /**
     * 显示帖子内容fragment
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void showTopicContentFragment(int userType, int spanType, int pvType, int sex, String postDesc, String postPvUrl) {
        mContentView.setBackgroundResource(RoleResLoader.getRoleDrawableResourceId(RoleResLoader.DynamicResName.POST_ITEM_BG, sex));
        if (userType == DataType.POST_USER) {
            //用户贴
            if (pvType == DataType.POST_VIDEO_TYPE) {
                //小视频
                PostUserVideoContentFragment userFragment = new PostUserVideoContentFragment();
                FragmentUtils.add(getFragmentManager(), userFragment, R.id.fl_topic_content);
                userFragment.bindTopicData(postDesc, postPvUrl);
            } else {
                //图片
                PostUserImageContentFragment userFragment = new PostUserImageContentFragment();
                FragmentUtils.add(getFragmentManager(), userFragment, R.id.fl_topic_content);
                userFragment.bindTopicData(spanType, postDesc, postPvUrl);
            }
        } else {
            //平台贴
            PostPlatformContentFragment platformFragment = new PostPlatformContentFragment();
            FragmentUtils.add(getFragmentManager(), platformFragment, R.id.fl_topic_content);
            platformFragment.loadH5Data(postDesc);
        }
    }

    /**
     * 绑定发帖人
     */
    private void bindUserInfoView(final String userId, String nickName, int sex, String photo, String date) {
        GlideUtils.loadSrcImage(ApUtils.getApp(), mAvatarView
                , CHelper.getOssThumbImageUrl(photo, getResources().getDimensionPixelOffset(R.dimen.avatar_size_38dp)));
        mTvName.setText(nickName);
        mTvName.setCompoundDrawablesWithIntrinsicBounds(0, 0
                , RoleResLoader.getRoleDrawableResourceId(RoleResLoader.DynamicResName.COMMUNITY_SEX_ICON, sex), 0);
        mTvDate.setText(date);
        mAvatarView.setOnClickListener(v -> UserDetailActivity.launchActivity(getActivity(), userId));
    }

    /**
     * 获取帖子评论列表
     */
    public PostDetailFragment bindTopicComments() {
        mAdapter.bindPostInfo(mPostId, mPostType);
        GetCommentRequest request = new GetCommentRequest();
        request.setForeignPkId(mPostId);
        request.setPageNum(mPageNum);
        request.setPageSize(AppConfig.PAGE_SIZE);
        request.setUserId(RcUser.getInstance().getUserId());
        mAdapter.notifyLoadMoreToLoading();
        OkRequest.getInstance().withUrl(UrlConfig.GET_COMMENT_LIST)
                .withRequest(request).doRequest(PostDetailFragment.class.getSimpleName(), new OkCallback<GetCommentResponse>() {
            @Override
            public void onResponse(GetCommentResponse response, String srcData) {
                if (response.isSuccess()) {
                    List<CommentParent> newData = response.getCommentParentList();
                    mAdapter.addData(newData);
                    showCommentTitleCount(response.getPageInfo());
                    if (newData.size() < AppConfig.PAGE_SIZE) {
                        mAdapter.loadMoreEnd(true);
                    } else {
                        mPageNum++;
                        mAdapter.loadMoreComplete();
                    }
                } else {
                    mAdapter.loadMoreFail();
                }
            }
        });
        return this;
    }

    /**
     * 显示评论总数
     *
     * @param pageInfo
     */
    private void showCommentTitleCount(PageInfo pageInfo) {
        if (pageInfo == null) {
            return;
        }
        mTvCommentTitle.setText(ApUtils.getApp()
                .getString(R.string.latest_comment_format, pageInfo.getTotalRecord()));
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_recycler_view, container, false);
        mRvDetail = view.findViewById(R.id.rv_recycler);

        mAdapter = new PostCommentAdapter(new ArrayList<CommentParent>());
        mAdapter.openLoadAnimation();
        mAdapter.setEnableLoadMore(true);
        mAdapter.setLoadMoreView(new PullLoadMoreView(RcUser.getInstance().getSex() == DataType.SEX_MALE
                ? R.layout.layout_load_more_view_male : R.layout.layout_load_more_view_female));
        mAdapter.setOnLoadMoreListener(this);

        mRvDetail.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRvDetail.setAdapter(mAdapter);

        mHeadView = inflater.inflate(R.layout.layout_post_detail_content, container, false);
        mContentView = mHeadView.findViewById(R.id.fl_topic_content);
        mAvatarView = mHeadView.findViewById(R.id.aiv_avatar);
        mSpcCountBar = mHeadView.findViewById(R.id.spc_count_bar);
        mInviteReplyView = mHeadView.findViewById(R.id.fl_invite_reply);
        mTvName = mHeadView.findViewById(R.id.tv_name);
        mTvDate = mHeadView.findViewById(R.id.tv_date);
        mTvCommentTitle = mHeadView.findViewById(R.id.tv_latest_comment);
        mAdapter.addHeaderView(mHeadView);

        return view;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(RefreshEvent event) {
        if (event.getType() == DataType.REFRESH_COMMENT_SUCCESS
                || event.getType() == DataType.REFRESH_REPLY_SUCCESS) {
            mPageNum = 1;
            mAdapter.setNewData(new ArrayList<CommentParent>());
            bindTopicComments();
        }
    }

    /**
     * 移动至评论区
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(CommentScrollEvent event) {
        if (event != null && isComment) {
            mRvDetail.postDelayed(()
                    -> mRvDetail.scrollBy(0, mHeadView.getHeight()), 200);
        }
    }

    @Override
    public void onLoadMoreRequested() {
        if (mPageNum > 1) {
            bindTopicComments();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
